library(scales)
library(egg)

# Function to make negotiation plots for a war
makeNegPlot = function(war_name) {
  
  onewar = d %>% filter(warName==war_name)
  
  # Get negotiation change dates
  changeDates = onewar$date[1]
  for (k in 2:nrow(onewar)) {
    
    if (onewar$negIE[k] == onewar$negIE[k-1]) {
      changeDates[k] = NA
    } else {
      changeDates[k-1] = format(onewar$date[k-1], "%Y-%m-%d")
      changeDates[k] = format(onewar$date[k], "%Y-%m-%d")
    }
  }
  changeDates[nrow(onewar)] = onewar$date[nrow(onewar)]
  
  negDates = data.frame(negIE=onewar$negIE, changeDates)
  
  # Fix for single-day negotiations
  daylist = list(); daylist[[1]] = negDates[1,]
  for (k in 2:(nrow(negDates)-1)) {
    
    if (negDates$negIE[k] != negDates$negIE[k-1] & negDates$negIE[k] != negDates$negIE[k+1]) {
      oneday = rbind(negDates[k,], negDates[k,])
    } else {
      oneday = negDates[k,]
    }
    
    daylist[[k]] = oneday
  }
  daylist[[nrow(negDates)]] = negDates[nrow(negDates),]
  negDates = do.call("rbind", daylist)
  negDates = negDates %>% drop_na(changeDates)
  
  # Turn into proper dataset format for plotting
  rseq = seq(1, nrow(negDates), by=2)
  
  changelist = list()
  for (r in 1:length(rseq)) {
    oneneg = negDates[rseq[r],]
    names(oneneg) = c("negType", "negStart")
    oneneg$negEnd = negDates$changeDates[rseq[r]+1]
    changelist[[r]] = oneneg
  }
  negChanges = do.call("rbind", changelist)
  negChanges$negType = factor(negChanges$negType, levels=c("None", "Internal", "External"),
                              labels=c("None", "Internal", "External"))
  
  negPlot = ggplot(negChanges, aes(x=negStart, xend=negEnd+1, y=negType, yend=negType)) + geom_segment(size=2) +
    scale_y_discrete(drop=FALSE) + theme_bw() + xlab("Date") + ylab("") +
    ggtitle(onewar$warName[1]) + theme() +
    theme(plot.title=element_text(size=10),
          axis.title.x = element_text(size = 9),
          axis.title.y = element_text(size = 9))
  
  if (nrow(onewar) < 14) {
    negPlot = negPlot + scale_x_date(labels=date_format("%m/%d/%Y"), breaks="3 days") 
  } else if (nrow(onewar) >= 14 & nrow(onewar) < 30) {
    negPlot = negPlot + scale_x_date(labels=date_format("%m/%d/%Y"), breaks="1 week") 
  } else if (nrow(onewar) >= 30 & nrow(onewar) < 180) {
    negPlot = negPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="1 month")
  } else if (nrow(onewar) >= 180 & nrow(onewar) < 360) {
    negPlot = negPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="2 months")
  } else if (nrow(onewar) >= 360 & nrow(onewar) < 900) {
    negPlot = negPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="4 months")
  } else {
    negPlot = negPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="1 year")
  }
  
  print(negPlot); return(negPlot)
}


# Function to make battle-related plots
makeFightPlot = function(war_name, file_name) {
  onewar = d %>% filter(warName==war_name)
  
  # Grids of fighting in each war
  onewarlong = onewar %>% pivot_longer(cols=c("outSum60", "AOS60", "outAll", "AOA", "nBattle"), names_to = "fight")
  onewarlong$fight = factor(onewarlong$fight, levels=c("outSum60", "AOS60", "outAll", "AOA", "nBattle"), 
                            labels=c("Momentum", "Recent imbalance", "Position", "Overall imbalance", "Active battles"))
  
  fightPlot = ggplot(onewarlong, aes(x=date, y=value)) + geom_line(size=0.5, lineend="round") + facet_grid(rows=vars(fight), scales="free") + theme_bw() +
    xlab("Date") + ylab("") + geom_hline(yintercept=0, lty=2) +
    theme(plot.title=element_text(size=10),
          axis.title.x = element_text(size = 9),
          axis.title.y = element_text(size = 9))
  
  if (nrow(onewarlong)/4 < 14) {
    fightPlot = fightPlot + scale_x_date(labels=date_format("%m/%d/%Y"), breaks="3 days") 
  } else if (nrow(onewarlong)/4 >= 14 & nrow(onewarlong)/4 < 30) {
    fightPlot = fightPlot + scale_x_date(labels=date_format("%m/%d/%Y"), breaks="1 week") 
  } else if (nrow(onewarlong)/4 >= 30 & nrow(onewarlong)/4 < 180) {
    fightPlot = fightPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="1 month")
  } else if (nrow(onewarlong)/4 >= 180 & nrow(onewarlong)/4 < 360) {
    fightPlot = fightPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="2 months")
  } else if (nrow(onewarlong)/4 >= 360 & nrow(onewarlong)/4 < 900) {
    fightPlot = fightPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="4 months")
  } else {
    fightPlot = fightPlot + scale_x_date(labels=date_format("%m/%Y"), breaks="1 year")
  }
  
  print(fightPlot)
}
  